﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ATEGo
{
    /// <summary>
    /// C#即时编译执行
    /// </summary>
    public class CSharpExecute
    {
        public static object EvalExpression(string code)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = false;
            parameters.ReferencedAssemblies.Add("System.dll");

            CompilerResults results = provider.CompileAssemblyFromSource(parameters, GenerateCode(code));
            if (results.Errors.HasErrors)
            {
                // 处理编译错误
                throw new InvalidOperationException("Expression cannot be evaluated.");
            }

            var assembly = results.CompiledAssembly;
            var eval = assembly.CreateInstance("EvalNamespace.EvalClass");
            var method = eval.GetType().GetMethod("Eval");
            return method.Invoke(eval, null);
        }
        private static string GenerateCode(string expression)
        {
            if (Regex.IsMatch(expression, "\\$\\$\\w*\\$\\$"))
            {
                MsgShow.Error("判断的语句中含有未赋值的变量，请修改脚本！");
                return @"
            using System;
            namespace EvalNamespace
            {
                public class EvalClass
                {
                    public object Eval()
                    {
                        return false;
                    }
                }
            }
        ";
            }
            else
                return @"
            using System;
            namespace EvalNamespace
            {
                public class EvalClass
                {
                    public object Eval()
                    {
                        return " + expression + @";
                    }
                }
            }
        ";
        }
    }
}
